package com.wbt.bambootown.ui.activity;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

import com.gyf.barlibrary.ImmersionBar;
import com.roughike.bottombar.BottomBar;
import com.roughike.bottombar.OnTabSelectListener;
import com.wbt.bambootown.FrameApp;
import com.wbt.bambootown.R;
import com.wbt.bambootown.hk.HC_DVRManager;
import com.wbt.bambootown.observable.CustomObserver;
import com.wbt.bambootown.observable.ObservableHelper;
import com.wbt.bambootown.receiver.NetworkBroadcastReceiver;
import com.wbt.bambootown.receiver.SignalRService;
import com.wbt.bambootown.ui.fragment.HomePageFragment;
import com.wbt.bambootown.ui.fragment.MineFragment;
import com.wbt.bambootown.ui.fragment.ObsDevicesFragment;
import com.wbt.bambootown.ui.fragment.RemoteControlFragment;
import com.wbt.bambootown.utils.EventCenter;

import java.util.List;

import butterknife.BindView;

public class MainActivity extends BaseActivity implements CustomObserver {
    @BindView(R.id.bottmBar)
    BottomBar mBottomBar;

    private Fragment[] fragments = new Fragment[4];
    private NetworkBroadcastReceiver networkBroadcastReceiver;

    private boolean isFirst = true; //网络状态第一次连接判断

    private long mExitTime = 0;

    @Override
    public void initStatusBar(ImmersionBar immersionBar) {

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initView() {
        ObservableHelper.addObserver(this , ObservableHelper.REGISTER_NETWORK_STATE_CHANGE);
        doBindService();
        registReceiver();
        fragments[0] = new HomePageFragment();
        fragments[1] = new RemoteControlFragment();
        fragments[2] = new ObsDevicesFragment();
        fragments[3] = new MineFragment();

        FragmentTransaction mFragmentTransaction = getSupportFragmentManager().beginTransaction();
        for (int i = 0; i < fragments.length; i++) {
            mFragmentTransaction.add(R.id.framelayout , fragments[i]);
        }
        mFragmentTransaction.show(fragments[0]);
        mFragmentTransaction.hide(fragments[1]);
        mFragmentTransaction.hide(fragments[0]);
        mFragmentTransaction.hide(fragments[3]);
        mFragmentTransaction.commit();

        mBottomBar.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelected(int tabId) {
                switch (tabId){
                    case R.id.tab_homePage:
                        showFragment(0);
                        break;
                    case R.id.tab_remoteControl:
                        showFragment(1);
                        break;
                    case R.id.tab_obsDevices:
                        showFragment(2);
                        break;
                    case R.id.tab_mine:
                        showFragment(3);
                        break;
                }

            }
        });

    }

    @Override
    public void initData() {

    }

    @Override
    public Object getContentView() {
        return R.layout.activity_main;
    }

    @Override
    public boolean isApplyEventBus() {
        return false;
    }

    @Override
    public boolean isApplyButterKnife() {
        return true;
    }

    @Override
    public void onEventCome(EventCenter eventCenter) {

    }

    private void showFragment(int position){
        FragmentTransaction mFragmentTransaction = getSupportFragmentManager().beginTransaction();
        for (int i = 0; i < fragments.length; i++) {
            if(position == i){
                mFragmentTransaction.show(fragments[i]);
                fragments[i].setUserVisibleHint(true);
            }else{
                mFragmentTransaction.hide(fragments[i]);
            }
        }
        mFragmentTransaction.commit();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        doBindService();
        registReceiver();
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(networkBroadcastReceiver);
    }

    @Override
    protected void onStop() {
        doUnbindService();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        new Thread() {
            @Override
            public void run() {
                HC_DVRManager.getInstance().logoutDevice();
                HC_DVRManager.getInstance().freeSDK();
            }
        }.start();
    }


    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - mExitTime > 2000) {
            Toast.makeText(this ,"再按一次退出程序" , Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            new Thread() {
                @Override
                public void run() {
                    HC_DVRManager.getInstance().stopPlay();
                }
            }.start();
            finish();
        }
    }

    @Override
    public void update(Object data, int type) {
        if((int)data == NetworkBroadcastReceiver.HAVE_NO_NETWORK){
            Log.e("Tag" , "网络连接断开");
        }else{
            Log.e("Tag" , "网络连接成功");
            if(isFirst){
                isFirst = false;
            }else{
                if(!FrameApp.mService.is_service_connected){
                    FrameApp.mService.startSignalR();
                }
            }
        }
    }


    private final ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            SignalRService.LocalBinder binder = (SignalRService.LocalBinder) service;
            FrameApp.mService = binder.getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            FrameApp.mService = null;
        }
    };

    private void doBindService(){
        Intent intent = new Intent(this, SignalRService.class);
        bindService(intent, mConnection, BIND_AUTO_CREATE);
    }

    private void doUnbindService() {
        if (FrameApp.mService.is_service_connected) {
            unbindService(mConnection);
        }
    }

    private void registReceiver(){
        //实例化IntentFilter对象
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        networkBroadcastReceiver = new NetworkBroadcastReceiver();
        //注册广播接收
        registerReceiver(networkBroadcastReceiver,filter);

    }


}
